import { ResPage } from "@/api/interface";
import { Blog } from "@/api/interface/blog";
import {
	addBlogApi,
	cancelTopBlogApi,
	deleteBlogApi,
	getBlogDetailApi,
	getBlogListApi,
	topBlogApi,
	updateBlogApi
} from "@/api/modules/blog";
import { RootThunkAction, store } from "@/redux";
import { RootDispatch } from "@/redux/interface";
import * as types from "@/redux/mutation-types";

export const setBlogList = (payload: ResPage<Blog>) => {
	return {
		type: types.SET_BLOG_LIST,
		payload
	};
};

export const setBlogDetail = (payload: Blog) => {
	return {
		type: types.SET_BLOG_DETAIL,
		payload
	};
};

export const getBlogList = (pageNum: number = 1, pageSize: number = 10, wrapper?: Partial<Blog>) => {
	store.dispatch(getList(pageNum, pageSize, wrapper));
};

export const getBlogDetail = (id: number) => {
	store.dispatch(getDetail(id));
};

export const addBlog = (blog: Blog) => {
	store.dispatch(add(blog));
};

export const updateBlog = (blog: Partial<Blog>) => {
	store.dispatch(update(blog));
};

export const removeBlog = (id: number) => {
	store.dispatch(remove(id));
};

export const topBlog = async (id: number) => {
	return await store.dispatch(top(id));
};

export const cancelTopBlog = async (id: number) => {
	return await store.dispatch(cancelTop(id));
};

export const getList = (pageNum: number, pageSize: number, wrapper?: Partial<Blog>): RootThunkAction => {
	return async (dispatch: RootDispatch<ResPage<Blog>>) => {
		const res = await getBlogListApi(pageNum, pageSize, wrapper);
		dispatch(setBlogList(res.data));
	};
};

export const getDetail = (id: number): RootThunkAction => {
	return async (dispatch: RootDispatch<Blog>) => {
		const res = await getBlogDetailApi(id);
		dispatch(setBlogDetail(res.data));
	};
};

export const add = (blog: Blog): RootThunkAction => {
	return async dispatch => {
		const res = await addBlogApi(blog);
		if (res.code === 200) getBlogList();
	};
};

export const update = (blog: Partial<Blog>): RootThunkAction => {
	return async dispatch => {
		const res = await updateBlogApi(blog);
		if (res.code === 200) getBlogList();
	};
};

export const remove = (id: number): RootThunkAction => {
	return async dispatch => {
		const res = await deleteBlogApi(id);
		if (res.code === 200) getBlogList();
	};
};

export const top = (id: number): RootThunkAction => {
	return async () => {
		const res = await topBlogApi(id);
		if (res.code === 200) return true;
		else return false;
	};
};

export const cancelTop = (id: number): RootThunkAction => {
	return async () => {
		const res = await cancelTopBlogApi(id);
		if (res.code === 200) return true;
		else return false;
	};
};
